package com.director.spring;

import com.director.core.DirectAction;
import com.director.core.DirectContext;
import com.director.core.DirectException;
import com.director.core.DirectMethod;
import com.director.core.DirectTransactionData;
import com.director.core.DirectTransactionResult;
import com.director.core.ExecutorAdapter;
import com.director.core.json.JsonParser;

import java.lang.reflect.InvocationTargetException;

/**
 * @author Simone Ricciardi
 * @version 1.0, 12/03/2011
 */
class DefaultActionExecutorAdapter implements ExecutorAdapter {

   private Object action;

   DefaultActionExecutorAdapter(Object action) {
      this.action = action;
   }

   @Override
   public DirectTransactionResult execute(DirectAction directAction, DirectMethod directMethod, DirectTransactionData data)
         throws DirectException {
      Object[] params = directMethod.parseParameters(data);
      Object result = invokeActionMethod(action, directAction, directMethod, params);
      JsonParser parser = DirectContext.get().getConfiguration().getParser();
      return parser.buildResult(directMethod, result);
   }

   private Object invokeActionMethod(Object action, DirectAction directAction, DirectMethod directMethod, Object[] params) {
      try {
         return directMethod.getMethod().invoke(action, params);
      } catch(InvocationTargetException e) {
         String message = "Cannot invoke the action method " + directMethod + " of the direct class " + directAction;
         throw new DirectException(message, e.getTargetException());
      } catch(Throwable e) {
         String message = "Cannot invoke the action method " + directMethod + " of the direct class " + directAction;
         throw new DirectException(message, e);
      }
   }
}
